<?php
/**
 * Powered By ThinkPHP 5.0.12
 * Copyright (c) 2017 http://www.bojuwang.net All rights reserved.
 * Created by PhpStorm.
 * Date: 2018/5/2 0002
 * Time: 下午 3:53
 * Author: NanTao <260053530@qq.com>
 */
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Wechat extends Controller
{
    protected $appid;
    protected $appsecret;
    public function _initialize()
    {
        parent::_initialize();
        $this->appid = sysconf('wx_appid');
        $this->appsecret = sysconf('wx_appsercet');
    }
    public function index()
    {
        if (!$this->checkSignature()){
            $this->createMenu();
            // $this->reponseMsg();
        }
    }
    public function reponseMsg()
    {
        //1.获取到微信推送过来post数据（xml格式）
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        $dataxml = json_decode(json_encode(simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA)),true);//转成数组，
        $FromUserName = $dataxml['FromUserName'];
        $MsgType = $dataxml['MsgType'];
        $Event = $dataxml['Event'];
        $EventKey = $dataxml['EventKey'];
        if ($MsgType == 'event')
        {
            if ($Event == 'subscribe' || $Event == 'SCAN')
            {
                // $this->postUser($FromUserName,$EventKey);
            }
        }

    }
    /*验证token*/
    public function checkSignature()
    {
        $request = Request::instance();
        $get = $request->param();
        $timestamp = $get['timestamp'];//timestamp其实就是一个时间戳
        $nonce = $get['nonce'];//nonce是一个随机参数
        $token = sysconf('wx_token');//这个token填写你在微信公众平台上写的那个值
        $signature = $get['signature'];//这个signature其实就是在微信公众平台已经加密好的字符串
        $array = [$token, $timestamp, $nonce];
        sort($array, SORT_STRING);
        $tmpstr = sha1(implode('', $array));
        if ($tmpstr == $signature && $get['echostr']) {
            // echo $get['echostr'];
            return true;
            exit();
        } else {
            return false;
        }
    }
    
    
    /*获取code*/
    public function getCode($parentId)
    {
        session('redirect_url',request()->url());
        //这个链接是获取code的链接 链接会带上code参数
        $redirectUri = sysconf('website').'/index/Wechat/getOpenid';
        $redirectUri = urlencode($redirectUri);
        $scope = "snsapi_userinfo";
        $state = $parentId;
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$redirectUri."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
        header("location:$url");exit();
    }
    /*获取用户openid*/
    public function getOpenId(Request $request)
    {
        $code = $request->get('code');
        $parentId = $request->get('state');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
        $result = $this->request_post($url);
        $result  = json_decode($result,true);
        $openid =  $result['openid'];
        $accessToken = $result['access_token'];
        $userInfo = $this->getUserInfo($accessToken,$openid);
        $user = Db::name('user')->where('wx_unionid',$userInfo['unionid'])->find();
        if ($user){
            if(!$user['wx_openid']){
                Db::name('user')->where('id',$user['id'])->update(['wx_openid'=>$openid]);
            }
            $this->bindUserParent($user['id'],$parentId);
            session('userId',$user['id']);
        } else {
            $data = [
                'user_name'=> get_user_username(),
                'wx_openid'=>$openid,
                'user_nickname' => $userInfo['nickname'],
                'sex' => $userInfo['sex'],
                'avatar' => get_remote_img($userInfo['headimgurl']),
                'wx_unionid' => $userInfo['unionid'],
                'wx_status'=>1
            ];
            $userId = Db::name('user')->insertGetId($data);
            $this->bindUserParent($userId,$parentId);
            session('userId',$userId);
        }
        $this->redirect(session('redirect_url'));
    }
  

    //绑定上级关系
    public function bindUserParent($userId,$parentId)
    {
        /*判断用户id是否等于上级parentId*/
        if ($userId != $parentId) {
            $userParent = Db::name('user_distribution')->where('next_user_id',$userId)->find();
            /*判断当前用户有没有上级*/
            if (!$userParent) {
                $parentData = get_user_model($parentId);
                /*判断上级是否是代言人*/
                if ($parentData['type'] == 1) {
                    $parent = Db::name('user_distribution')->where('next_user_id',$parentId)->find();
                    $classList = $parent ? $parent['class_list']: ','.$parentId.',';
                    $data = [
                        'user_id'=> $parentId,
                        'next_user_id'=> $userId,
                        'class_list'=>$classList.$userId.',',
                        'class_layer'=>$parent['class_layer'] + 1
                    ];
                    if (Db::name('user_distribution')->where('next_user_id',$userId)->find()) {
                        Db::name('user_distribution')->where('next_user_id',$userId)->update($data);
                    } else {
                        Db::name('user_distribution')->insert($data);
                    }
                }
            }
        }
    }
    /*获取access_token*/
    public function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
        $accessToken = $this->request_get($url);
        $res = json_decode($accessToken,true);
        cookie('accressToken',$res['access_token'],7200);
        return $res['access_token'];
    }
    /*获取用户的详细信息*/
    public function getUserInfo($accessToken,$openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$accessToken."&openid=".$openid."&lang=zh_CN";
        $res = $this->request_get($url);
        $res = json_decode($res,true);
        return $res;
    }
    //创建微信菜单
    public function  createMenu()
    {
        header('content-type:text/html;charset=utf-8');
        $access_token = $this ->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $result = $this->request_post($url,sysconf('wx_menu'));
        // var_dump($result);
    }
    /*生成带参数的二维码*/
    public function getQrcode($scene)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->getAccessToken();
        $data = [
            "action_name" =>"QR_LIMIT_STR_SCENE",
            "action_info" => [
                "scene" => ["scene_str"=>$scene]
            ],
        ];
        $data = json_encode($data);
        $result = $this->request_post($url,$data);
        $result = json_decode($result,true);

        $ticket = UrlEncode($result['ticket']);
        return $ticket;
    }
    /*获取Ticket*/
    public function getJsapiTicket()
    {

        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$accessToken."&type=jsapi";
        $result = $this->request_get($url);
        $result = json_decode($result,true);
        $jsapiTicket = $result['ticket'];
        return $jsapiTicket;
    }
    /*生成随机字符串*/
    public function getRandCode($length=16)
    {
        $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $hash = '';
        $max = strlen($str) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $str[mt_rand(0, $max)];
        }
        return $hash;
    }
    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
    public function request_post($url,$data)
    {
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //启用时会发送一个常规的POST请求,为1或者为true
        if(!empty($data)){
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//需要要传送的内容
        }
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }
    /**
     * 模拟get进行url请求
     * @param string $url
     */
    public function request_get($url){
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }

}